#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/types.h>
#include "simulator.h"
#include "config.h"
#include "errno.h"

int simulator_id;

int simulator_start() {
	const char *simulator_cmd = config_get("SIMULATOR_CMD", 0);
	
	if (simulator_cmd == 0) {
		fprintf(stderr, "chipmuck: cannot find SIMULATOR_CMD in config file.\n");
		return -E_NO_SIMULATOR_FIND;
	}
	
	if ((simulator_id = fork()) == 0) {
		if (system(simulator_cmd) < 0)
			fprintf(stderr, "chipmuck: unable to execute simulator %s.\n", simulator_cmd);
		exit(0);
	}
	else if (simulator_id == -1) {
		fprintf(stderr, "chipmuck: unable to fork the simulator.\n");
		return -E_NO_SIMULATOR_FIND;
	}
	return 0;
}

void simulator_stop() {
	if (waitpid(simulator_id, 0, WNOHANG) == 0) {
		kill(simulator_id, SIGKILL);
	}
}
